package cf

import (
	"context"
	"fmt"
)

var (
	lifeCycleHandlers []lifeCycleWrapper // 用户注册的生命周期回调函数，待用户注册
)

// 生命周期回调接口
type LifeCycleHandler interface {
	Invoke(ctx context.Context)
}

type fcLifeCycleHandler func(context.Context)

func (handler fcLifeCycleHandler) Invoke(ctx context.Context) {
	handler(ctx)
}

func errorLifeCycleHandler(e error) fcLifeCycleHandler {
	return func(ctx context.Context) {
		panic(e)
	}
}

// 不同生命周期对应的处理函数类型
const (
	handleFunction int = iota
	initializerFunction
	preStopFunction
)

type lifeCycleWrapper struct {
	lcHandler fcLifeCycleHandler
	lifeType  int
}

// 用户调用，用于注册生命周期回调函数
// 限定 handler 类型，让不符合规范的 lifeHandler 不能通过编译

func RegisterInitializerFunction(handler fcLifeCycleHandler) {
	registerLifeCycleHandler(handler, initializerFunction)
}

func RegisterPreStopFunction(handler fcLifeCycleHandler) {
	registerLifeCycleHandler(handler, preStopFunction)
}

func registerLifeCycleHandler(handler fcLifeCycleHandler, lType int) {
	lifeCycleHandlers = append(lifeCycleHandlers, lifeCycleWrapper{handler, lType})
}

func newLifeCycleHandler(handlerFunc fcLifeCycleHandler) LifeCycleHandler {
	if handlerFunc == nil {
		return errorLifeCycleHandler(fmt.Errorf("handler is nil"))
	}
	return handlerFunc
}
